package com.XDApp.xdbase.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.ContentValues;
import android.content.Intent;
import android.text.TextUtils;

public class XMLParserUtil {

  /**
   * 
   * @param parser
   * @param xTagToDBTag
   * @param dispensable
   * @return
   * @throws XmlPullParserException
   * @throws IOException
   */
  public static List<ContentValues> parseListXml(XmlPullParser parser, HashMap<String, String> xTagToDBTag)
      throws XmlPullParserException, IOException {
    List<ContentValues> list = new ArrayList<ContentValues>();
    int eventType = parser.next();
    int targetDepth = -1;
    ContentValues val = new ContentValues();
    while (eventType != XmlPullParser.END_DOCUMENT) {
      if (eventType == XmlPullParser.START_TAG) {
        String tagName = parser.getName();
        String dTagName = xTagToDBTag.get(tagName);
        if (!TextUtils.isEmpty(dTagName) && parser.getDepth() > 2) {
          if (targetDepth == -1) targetDepth = parser.getDepth();
          parser.next();
          val.put(dTagName, parser.getText());
        }
      } else if (eventType == XmlPullParser.END_TAG) {
        if (parser.getDepth() == targetDepth - 1) {
          list.add(val);
          val = new ContentValues();
        }
      }
      eventType = parser.next();
    }
    return list;
  }

  public static Intent parseStateAndPhrase(XmlPullParser parser) throws Exception {
    Intent i = new Intent();
    int eventType;
    int code = -1;
    String errorMsg = null;
    while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) {
      if (eventType == XmlPullParser.START_TAG) {
        String tagName = parser.getName();
        parser.next();
        if ("RESPONSECODE".equalsIgnoreCase(tagName)) {
          code = Integer.parseInt(parser.getText());
          i.putExtra("state", code);
          if (200 == code || null != errorMsg) break;
        } else if ("ERRORMESSAGE".equalsIgnoreCase(tagName)) {
          errorMsg = parser.getText();
          i.putExtra("phrase", errorMsg);
          if (code != -1) break;
        }
      }
    }
    return i;
  }

  public static List<ContentValues> parseTextXml(XmlPullParser parser, HashMap<String, String> xTagToDBTag,
      String dbKey, String dbValue) throws XmlPullParserException, IOException {
    List<ContentValues> list = new ArrayList<ContentValues>();
    int eventType = parser.next();
    ArrayList<String> xKey = new ArrayList<String>(xTagToDBTag.keySet());
    while (eventType != XmlPullParser.END_DOCUMENT) {
      if (eventType == XmlPullParser.START_TAG) {
        String tagName = parser.getName();
        String dTagName = xTagToDBTag.get(tagName);
        if (!TextUtils.isEmpty(dTagName)) {
          ContentValues val = new ContentValues();
          val.put(dbKey, dTagName);
          parser.next();
          val.put(dbValue, parser.getText());
          parser.next();
          xKey.remove(tagName);
          list.add(val);
        }
      }
      if (xKey.size() == 0) break;
      eventType = parser.next();
    }
    return list;
  }

  public static Element domParseXML(InputStream in) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 取得DocumentBuilderFactory实例
    DocumentBuilder builder = factory.newDocumentBuilder(); // 从factory获取DocumentBuilder实例
    Document doc = builder.parse(in); // 解析输入流 得到Document实例
    return doc.getDocumentElement();
  }

  public static String getElementValue(Node node) {
    if (node.getNodeType() == Node.TEXT_NODE) return node.getNodeValue();
    if (node.hasChildNodes()) {
      Node child = node.getFirstChild();
      if (child.getNodeType() == Node.TEXT_NODE) return child.getNodeValue();
    }
    return "";
  }

  public static HashMap<String, String> parseXmlToMap(XmlPullParser parser) throws Exception {
    HashMap<String, String> map = new HashMap<String, String>();
    int eventType;
    JSONObject json = new JSONObject();
    while ((eventType = parser.getEventType()) != XmlPullParser.END_DOCUMENT) {
      if (eventType == XmlPullParser.TEXT) {
        String value = parser.getText();
        parser.next();
        map.put(parser.getName(), value);
        json.put(parser.getName(), value);
      }
      parser.next();
    }
//    LogUtil.e(json.toString());
    return map;
  }

}
